import { prisma } from '@/utils/backend/db'
import { HttpStatus } from '@/utils/httpStatus'
import { NextResponse } from 'next/server'

export async function GET(req: Request, { params }: { params: { id: string } }) {
  try {
    const id = parseInt(params.id)
    const user = await prisma.user.findUnique({
      where: { id }
    })

    if (!user) {
      return NextResponse.json(
        {
          success: false,
          message: '用户不存在'
        },
        { status: HttpStatus.NOT_FOUND }
      )
    }

    return NextResponse.json({
      success: true,
      message: '获取成功',
      data: user
    })
  } catch (error) {
    console.error('Get user failed:', error)
    return NextResponse.json(
      {
        success: false,
        message: '获取用户信息失败'
      },
      { status: HttpStatus.INTERNAL_SERVER_ERROR }
    )
  }
}

export async function PATCH(req: Request, { params }: { params: { id: string } }) {
  try {
    const id = parseInt(params.id)
    const data = await req.json()

    const user = await prisma.user.update({
      where: { id },
      data
    })

    return NextResponse.json({
      success: true,
      message: '更新成功',
      data: user
    })
  } catch (error) {
    console.error('Update user failed:', error)
    return NextResponse.json(
      {
        success: false,
        message: '更新用户信息失败'
      },
      { status: HttpStatus.INTERNAL_SERVER_ERROR }
    )
  }
}

export async function DELETE(req: Request, { params }: { params: { id: string } }) {
  try {
    const id = parseInt(params.id)
    await prisma.user.delete({
      where: { id }
    })

    return NextResponse.json({
      success: true,
      message: '删除成功'
    })
  } catch (error) {
    console.error('Delete user failed:', error)
    return NextResponse.json(
      {
        success: false,
        message: '删除用户失败'
      },
      { status: HttpStatus.INTERNAL_SERVER_ERROR }
    )
  }
}
